﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Caching;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.CCFlow;
using BEGDC.CC.Web.View;

namespace BEGDC.CC.Web.UserControls
{
    /// <summary>
    ///		Summary description for FileInfo.
    /// </summary>
    public class CommonAttachment : System.Web.UI.UserControl
    {
        protected System.Web.UI.WebControls.Button btnAttach;
        protected System.Web.UI.WebControls.DataGrid dgAttachment;

        protected System.Web.UI.HtmlControls.HtmlInputFile fileTemplate; //if template ID=0
        protected System.Web.UI.WebControls.DropDownList drFlowType;
        protected System.Web.UI.WebControls.DropDownList drSample;
        protected System.Web.UI.WebControls.DropDownList drTemplateType;

        protected System.Web.UI.HtmlControls.HtmlInputFile fileSummary;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileAgenda;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileBudget;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileVisa;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileGift;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileContract;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileOthers;

        protected System.Web.UI.HtmlControls.HtmlGenericControl tr_Attach;
        protected System.Web.UI.HtmlControls.HtmlTableRow trTemplate;

        protected System.Web.UI.HtmlControls.HtmlTableRow trSummary;
        protected System.Web.UI.HtmlControls.HtmlTableRow trAgenda;
        protected System.Web.UI.HtmlControls.HtmlTableRow trBudget;
        protected System.Web.UI.HtmlControls.HtmlTableRow trVisa;
        protected System.Web.UI.HtmlControls.HtmlTableRow trGift;
        protected System.Web.UI.HtmlControls.HtmlTableRow trContract;
        protected System.Web.UI.HtmlControls.HtmlTableRow trOthers;
        protected System.Web.UI.HtmlControls.HtmlTableRow trCVFeedback;
        protected System.Web.UI.HtmlControls.HtmlTableRow trEvMeetingMinutes;

        protected System.Web.UI.WebControls.Label lblTitle;
        protected System.Web.UI.HtmlControls.HtmlTable tbUpload;
        protected System.Web.UI.WebControls.DataGrid dgTemplate;
        protected System.Web.UI.WebControls.Label lblListName;
        protected System.Web.UI.WebControls.Label lblUpload;
        protected System.Web.UI.WebControls.Label lbAppNo;

        protected System.Web.UI.HtmlControls.HtmlGenericControl dvAttachmentPane;
        protected System.Web.UI.HtmlControls.HtmlGenericControl dvWelcome;


        protected System.Web.UI.HtmlControls.HtmlTable tableAttachmentTitle;


        #region varialbes
        private bool readOnly;
        private int id;
        protected System.Web.UI.WebControls.HyperLink lnkAgendaTemp;
        protected System.Web.UI.WebControls.HyperLink lnkAgendaSample;
        protected System.Web.UI.WebControls.HyperLink lnkBudgetTemp;
        protected System.Web.UI.WebControls.HyperLink lnkBudgetSample;
        protected System.Web.UI.WebControls.HyperLink lnkVisaTemp;
        protected System.Web.UI.WebControls.HyperLink lnkVisaSample;
        protected System.Web.UI.WebControls.HyperLink lnkGiftTemp;
        protected System.Web.UI.WebControls.HyperLink lnkGiftSample;
        protected System.Web.UI.WebControls.HyperLink lnkContractTemp;
        protected System.Web.UI.WebControls.HyperLink lnkContractSample;
        protected System.Web.UI.WebControls.HyperLink lnkHotelTemp;
        protected System.Web.UI.WebControls.HyperLink lnkHotelSample;
        protected System.Web.UI.WebControls.HyperLink lnkVehicleTemp;
        protected System.Web.UI.WebControls.HyperLink lnkVehicleSample;
        protected System.Web.UI.WebControls.HyperLink lnkDemoTemp;
        protected System.Web.UI.WebControls.HyperLink lnkDemoSample;
        protected System.Web.UI.WebControls.HyperLink lnkASBVisitTemp;
        protected System.Web.UI.WebControls.HyperLink lnkASBVisitSample;
        protected System.Web.UI.WebControls.HyperLink lnkOCOTemplate;
        protected System.Web.UI.WebControls.HyperLink lnkExecutiveTemp;
        protected System.Web.UI.WebControls.HyperLink lnkExecutiveSample;
        protected System.Web.UI.HtmlControls.HtmlTableRow trHotel;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileHotel;
        protected System.Web.UI.HtmlControls.HtmlTableRow trVehicle;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileVehicle;
        protected System.Web.UI.HtmlControls.HtmlTableRow trDemo;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileDemo;
        protected System.Web.UI.HtmlControls.HtmlTableRow trASBVisit;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileASBVisit;
        protected System.Web.UI.WebControls.Label lb_Warning;
        protected System.Web.UI.WebControls.Label lblAgenda;
        protected System.Web.UI.WebControls.Label lblOthers;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileCVFeedback;
        protected System.Web.UI.HtmlControls.HtmlInputFile fileEvMeetingMinutes;
        protected System.Web.UI.WebControls.HyperLink lnkCVFeedbackSample;
        protected System.Web.UI.WebControls.HyperLink lnkEvMeetingMinutesSample;
        protected System.Web.UI.WebControls.HyperLink lnkCVFeedbackTemp;
        protected System.Web.UI.WebControls.HyperLink lnkEvMeetingMinutesTemp;

        private UploadType uploadType;

        protected new virtual BEGDC.CC.Entity.Application Application
        {
            get
            {
                if (Session[this.id.ToString()] != null)
                    return (BEGDC.CC.Entity.Application)Session[this.id.ToString()];
                return null;
            }
            set { Session[this.id.ToString()] = value; }
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        private string _Sorting
        {
            get
            {
                if (ViewState["Sorting"] == null) return string.Empty;

                return ViewState["Sorting"].ToString();
            }
            set { ViewState["Sorting"] = value; }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {


            DocumentManagement docMgnPage = null;
            try
            {
                docMgnPage = (DocumentManagement)this.Parent.Page;
            }
            catch
            { }

            if (docMgnPage != null)
            {
                this.id = docMgnPage.TempID;
                this.uploadType = docMgnPage.UpldType;
                this.readOnly = docMgnPage.ReadOnly;

                dvWelcome.Visible = false;
                dvAttachmentPane.Visible = true;
                if (!Page.IsPostBack)
                {
                    BindAttachType();
                    AddAppType();
                }
            }
            else
            {
                //把AttachmentPane转移到Application页面上
                var appID = Request.QueryString["AppID"];
                dvWelcome.Visible = appID == null;
                dvAttachmentPane.Visible = appID != null;
                if (!dvAttachmentPane.Visible)
                    return;

                InitParameters();
            }

            if (!Page.IsPostBack)
            {
                this.btnAttach.Attributes.Add("onclick", "javascript:CheckFile();");
                ShowUploads();
                GetTemplateLinks();
                BindAttachment();

                if (this.Application != null)
                {
                    this.lbAppNo.Text = this.Application.AppNo;
                    this.lb_Warning.Visible = true;
                }
                else
                {
                    this.lb_Warning.Visible = false;
                }
            }

            //Close，hiden Attachment
            string strFlowId = Request.QueryString["FlowID"];
            if (strFlowId + string.Empty != string.Empty)
            {
                int flowId = Convert.ToInt32(strFlowId);
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                FlowInstance instance = queryService.QueryFlowInstanceByFlowId(flowId);
                if (instance.CurrentStep.StepCode == WorkTransition.EV_Close ||
                    instance.CurrentStep.StepCode == WorkTransition.CR_CloseApp ||
                    instance.CurrentStep.StepCode == WorkTransition.OCR_CloseApp ||
                    instance.CurrentStep.StepCode == WorkTransition.OCV_Close)
                {
                    if (instance.Application.ApplicationType == WorkflowTypes.EV && Request.QueryString["State"].ToString() == BEGDC.CC.BL.Workflow.Action.Query)
                    {
                        tableAttachmentTitle.Visible = true;
                        tr_Attach.Visible = true;
                        tbUpload.Visible = true;
                    }
                    else
                    {
                        tableAttachmentTitle.Visible = false;
                        tr_Attach.Visible = false;
                        tbUpload.Visible = false;
                    }
                }
            }
        }


        #region Added by Joe 2007/7/4
        private void InitParameters()
        {
            this.uploadType = GetUploadType();

            if (Request.QueryString["AppID"] + string.Empty != string.Empty)
            {
                this.id = Convert.ToInt32(Request.QueryString["AppID"]);
            }
            else
            {
                this.id = 0;
            }

            this.readOnly = IsReadOnly();
        }

        private UploadType GetUploadType()
        {
            if (Request.QueryString["PDType"] + string.Empty != string.Empty)
            {
                string type = Request.QueryString["PDType"];
                if (type == WorkflowTypes.EV || type == WorkflowTypes.CV || type == WorkflowTypes.CR || type == WorkflowTypes.CO || type == WorkflowTypes.OCR || type == WorkflowTypes.OCV || type == WorkflowTypes.EBD || type == WorkflowTypes.ESC || type == WorkflowTypes.EBDCV || type == WorkflowTypes.ESCCV)
                {
                    return UploadType.APPLICATION;
                }
                else
                {
                    return UploadType.ACTIONPOINT;
                }
            }
            else
            {
                return UploadType.TEMPLATE;
            }
        }

        private bool IsReadOnly()
        {
            BEGDC.CC.Web.UserControls.IPageAccess page = (UserControls.IPageAccess)this.Page;
            if (page != null && page.Access != null)
            {
                //return page.Access.IsReadOnly;
                return page.Access.IsAttachmentReadOnly;
            }
            else
                return false;
        }
        #endregion

        #region bind attachment type dropdown list
        private void BindAttachType()
        {
            ListItem item;
            BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
            IList list = utility.BuildDicList(BEGDC.CC.BL.Common.DicType.ATTACHMENTTYPE);
            for (int i = 0; i < list.Count; i++)
            {

                if (((DicItem)list[i]).DicItemKey == "SUMMARY" || ((DicItem)list[i]).DicItemKey == "OTHERS")
                {
                    continue;
                }
                if (((DicItem)list[i]).DicItemKey == "HOTEL" || ((DicItem)list[i]).DicItemKey == "VEHICLE" || ((DicItem)list[i]).DicItemKey == "ASBVISIT" || ((DicItem)list[i]).DicItemKey == "DEMOCENTER")
                {
                    if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.OCOBusinessAdmin))
                    {

                        item = new ListItem();
                        item.Value = ((DicItem)list[i]).DicItemKey;
                        item.Text = ((DicItem)list[i]).Description;
                        this.drTemplateType.Items.Add(item);
                    }
                }
                else if (((DicItem)list[i]).DicItemKey == "CONTRACT")
                {
                    if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.BusinessAdmin))
                    {

                        item = new ListItem();
                        item.Value = ((DicItem)list[i]).DicItemKey;
                        item.Text = ((DicItem)list[i]).Description;
                        this.drTemplateType.Items.Add(item);
                    }
                }
                else
                {
                    item = new ListItem();
                    item.Value = ((DicItem)list[i]).DicItemKey;
                    item.Text = ((DicItem)list[i]).Description;
                    this.drTemplateType.Items.Add(item);

                }



            }



        }
        private void AddAppType()
        {
            ListItem item;
            if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.BusinessAdmin))
            {
                item = new ListItem("EV", "EV");
                this.drFlowType.Items.Add(item);
                //item = new ListItem("CV", "CV");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("CR-A", "CR-A");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("CR-B", "CR-B");
                //this.drFlowType.Items.Add(item);
                item = new ListItem("CR", "CR");
                this.drFlowType.Items.Add(item);
                //item = new ListItem("CO", "CO");
                //this.drFlowType.Items.Add(item);
            }
            if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.OCOBusinessAdmin))
            {

                //item = new ListItem("OCR-A", "OCR-A");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("OCR-B", "OCR-B");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("OCV", "OCV");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("EBD-A", "EBD-A");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("EBD-B", "EBD-B");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("ESC-A", "ESC-A");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("ESC-B", "ESC-B");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("EBDCV", "EBDCV");
                //this.drFlowType.Items.Add(item);
                //item = new ListItem("ESCCV", "ESCCV");
                //this.drFlowType.Items.Add(item);
                item = new ListItem("IBGCR", "IBGCR");
                this.drFlowType.Items.Add(item);
                item = new ListItem("IBGCV", "IBGCV");
                this.drFlowType.Items.Add(item);
            }
        }
        #endregion

        #region GetTemplateLinks, Display Template or Sample links
        private void GetTemplateLinks()
        {
            DataTable table;
            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            if (this.uploadType != UploadType.APPLICATION)
                return;


            if (Cache["Template"] != null)
                table = (DataTable)Cache["Template"];
            else
            {
                AddTemplateCache(null);
                table = (DataTable)Cache["Template"];
            }

            if (table == null)
                return;

            string navUrl = "";
            string strTemplate = "../images/template.gif";
            string strSample = "../images/Icon_Sample.jpg";
            string strTarget = "_self";
            Application app = query.GetApplication(this.id);
            string appType = app.ApplicationType.ToUpper();

            #region CR or OCR
            if (appType == "CR")
            {
                //if (app.IsTransition)
                //{
                //    appType = "CR-A";
                //}
                //else
                //{
                //    appType = "CR-B";
                //}
            }
            else if (appType == "OCR")
            {
                //if (app.IsTransition)
                //{
                //    appType = "OCR-A";
                //}
                //else
                //{
                //    appType = "OCR-B";
                //}
                appType = "IBGCR";
            }
            else if (appType == "OCV")
            {
                appType = "IBGCV";
            }
            else if (appType == "EBD")
            {
                if (app.IsTransition)
                {
                    appType = "EBD-A";
                }
                else
                {
                    appType = "EBD-B";
                }
            }
            else if (appType == "ESC")
            {
                if (app.IsTransition)
                {
                    appType = "ESC-A";
                }
                else
                {
                    appType = "ESC-B";
                }
            }
            #endregion
            //if (appType == "OCV" || appType == "OCR-A" || appType == "OCR-B" || appType == "EBD-A" || appType == "EBD-B" || appType == "ESC-A" || appType == "ESC-B" || appType == "EBDCV" || appType == "ESCCV")
            if (appType == "IBGCV" || appType == "OCR-A" || appType == "IBGCR" || appType == "EBD-A" || appType == "EBD-B" || appType == "ESC-A" || appType == "ESC-B" || appType == "EBDCV" || appType == "ESCCV")
            {
                this.lnkOCOTemplate.Visible = true;
                this.lblOthers.Text = "Other Documents(公司介绍PPT,SSME演示文稿等):";
                //if (appType == "OCR-A" || appType == "OCR-B" || appType == "EBD-A" || appType == "EBD-B" || appType == "ESC-A" || appType == "ESC-B")
                if (appType == "OCR-A" || appType == "IBGCR" || appType == "EBD-A" || appType == "EBD-B" || appType == "ESC-A" || appType == "ESC-B")
                {
                    this.lblAgenda.Text = "Agenda(附拜访董事长/总裁申请单):";
                }
                //				else if (appType=="EBD-A" || appType=="EBD-B")
                //				{
                //					this.lblAgenda.Text="Agenda(附拜访董事长/总裁申请单):";
                //				}
                //				else if (appType=="ESC-A" || appType=="ESC-B")
                //				{
                //					this.lblAgenda.Text="Agenda(附拜访董事长/总裁申请单):";
                //				}
                //				else if (appType=="ESC-A" || appType=="ESC-B")
                //				{
                //					this.lblAgenda.Text="Agenda(附拜访董事长/总裁申请单):";
                //				}
                else
                {
                    this.lblAgenda.Text = "Agenda(行程表):";
                }
            }
            else
            {
                this.lnkOCOTemplate.Visible = false;
                this.lblAgenda.Text = "Agenda:<br/>行程表";
                this.lblOthers.Text = "Other Documents:<br/>其他文档";
            }

            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (table.Rows[i]["TemplateForApp"].ToString() != appType)
                    continue;

                navUrl = string.Format("../Workflow/AttachmentExport.aspx?FileID={0}&Type=Template", table.Rows[i]["TemplateID"].ToString());
                if (table.Rows[i]["TemplateOrSample"].ToString().ToUpper() == "TEMPLATE")
                {
                    #region Template
                    string aa = table.Rows[i]["TemplateType"].ToString().ToUpper();
                    switch (table.Rows[i]["TemplateType"].ToString().ToUpper())
                    {
                        case "AGENDA":
                            this.lnkAgendaTemp.ImageUrl = strTemplate;
                            this.lnkAgendaTemp.NavigateUrl = navUrl;
                            this.lnkAgendaTemp.Target = strTarget;
                            break;
                        case "BUDGET":
                            this.lnkBudgetTemp.ImageUrl = strTemplate;
                            this.lnkBudgetTemp.NavigateUrl = navUrl;
                            this.lnkBudgetTemp.Target = strTarget;

                            break;
                        case "VISA":
                            this.lnkVisaTemp.ImageUrl = strTemplate;
                            this.lnkVisaTemp.NavigateUrl = navUrl;
                            this.lnkVisaTemp.Target = strTarget;

                            break;
                        case "GIFT":
                            this.lnkGiftTemp.ImageUrl = strTemplate;
                            this.lnkGiftTemp.NavigateUrl = navUrl;
                            this.lnkGiftTemp.Target = strTarget;
                            break;
                        case "CONTRACT":
                            this.lnkContractTemp.ImageUrl = strTemplate;
                            this.lnkContractTemp.NavigateUrl = navUrl;
                            this.lnkContractTemp.Target = strTarget;
                            break;

                        //<--Joan 2007/8/2
                        case "HOTEL":
                            this.lnkHotelTemp.ImageUrl = strTemplate;
                            this.lnkHotelTemp.NavigateUrl = navUrl;
                            this.lnkHotelTemp.Target = strTarget;
                            break;
                        case "VEHICLE":
                            this.lnkVehicleTemp.ImageUrl = strTemplate;
                            this.lnkVehicleTemp.NavigateUrl = navUrl;
                            this.lnkVehicleTemp.Target = strTarget;
                            break;
                        case "DEMOCENTER":
                            this.lnkDemoTemp.ImageUrl = strTemplate;
                            this.lnkDemoTemp.NavigateUrl = navUrl;
                            this.lnkDemoTemp.Target = strTarget;
                            break;
                        case "ASBVISIT":
                            this.lnkASBVisitTemp.ImageUrl = strTemplate;
                            this.lnkASBVisitTemp.NavigateUrl = navUrl;
                            this.lnkASBVisitTemp.Target = strTarget;
                            break;
                        case "EXECUTIVESUMMARY":
                            this.lnkExecutiveTemp.ImageUrl = strTemplate;
                            this.lnkExecutiveTemp.NavigateUrl = navUrl;
                            this.lnkExecutiveTemp.Target = strTarget;
                            break;
                        case "CRFEEDBACK":
                            this.lnkCVFeedbackTemp.ImageUrl = strTemplate;
                            this.lnkCVFeedbackTemp.NavigateUrl = navUrl;
                            this.lnkCVFeedbackTemp.Target = strTarget;
                            break;
                        case "EVMEETINGMINUTES":
                            this.lnkEvMeetingMinutesTemp.ImageUrl = strTemplate;
                            this.lnkEvMeetingMinutesTemp.NavigateUrl = navUrl;
                            this.lnkEvMeetingMinutesTemp.Target = strTarget;
                            break;
                        //-->end

                        default:
                            break;

                    }
                    #endregion
                }
                else
                {
                    #region Sample
                    switch (table.Rows[i]["TemplateType"].ToString().ToUpper())
                    {
                        case "AGENDA":
                            this.lnkAgendaSample.ImageUrl = strSample;
                            this.lnkAgendaSample.NavigateUrl = navUrl;
                            this.lnkAgendaSample.Target = strTarget;
                            break;
                        case "BUDGET":
                            this.lnkBudgetSample.ImageUrl = strSample;
                            this.lnkBudgetSample.NavigateUrl = navUrl;
                            this.lnkBudgetSample.Target = strTarget;
                            break;
                        case "VISA":
                            this.lnkVisaSample.ImageUrl = strSample;
                            this.lnkVisaSample.NavigateUrl = navUrl;
                            this.lnkVisaSample.Target = strTarget;
                            break;
                        case "GIFT":
                            this.lnkGiftSample.ImageUrl = strSample;
                            this.lnkGiftSample.NavigateUrl = navUrl;
                            this.lnkGiftSample.Target = strTarget;
                            break;
                        case "CONTRACT":
                            this.lnkContractSample.ImageUrl = strSample;
                            this.lnkContractSample.NavigateUrl = navUrl;
                            this.lnkContractSample.Target = strTarget;
                            break;

                        //<--Joan 2007/8/2
                        case "HOTEL":
                            this.lnkHotelSample.ImageUrl = strSample;
                            this.lnkHotelSample.NavigateUrl = navUrl;
                            this.lnkHotelSample.Target = strTarget;
                            break;
                        case "VEHICLE":
                            this.lnkVehicleSample.ImageUrl = strSample;
                            this.lnkVehicleSample.NavigateUrl = navUrl;
                            this.lnkVehicleSample.Target = strTarget;
                            break;
                        case "DEMOCENTER":
                            this.lnkDemoSample.ImageUrl = strSample;
                            this.lnkDemoSample.NavigateUrl = navUrl;
                            this.lnkDemoSample.Target = strTarget;
                            break;
                        case "ASBVISIT":
                            this.lnkASBVisitSample.ImageUrl = strSample;
                            this.lnkASBVisitSample.NavigateUrl = navUrl;
                            this.lnkASBVisitSample.Target = strTarget;
                            break;
                        case "EXECUTIVESUMMARY":
                            this.lnkExecutiveSample.ImageUrl = strSample;
                            this.lnkExecutiveSample.NavigateUrl = navUrl;
                            this.lnkExecutiveSample.Target = strTarget;
                            break;
                        //-->end
                        case "CRFEEDBACK":
                            this.lnkCVFeedbackSample.ImageUrl = strSample;
                            this.lnkCVFeedbackSample.NavigateUrl = navUrl;
                            this.lnkCVFeedbackSample.Target = strTarget;
                            break;
                        case "EVMEETINGMINUTES":
                            this.lnkEvMeetingMinutesSample.ImageUrl = strSample;
                            this.lnkEvMeetingMinutesSample.NavigateUrl = navUrl;
                            this.lnkEvMeetingMinutesSample.Target = strTarget;
                            break;
                        default:
                            break;
                    }
                    #endregion
                }
            }





        }

        #endregion

        #region Show or hide upload field
        private bool IsApplicationOwner()
        {
            if (this.Application == null) return false;
            if (HttpContext.Current.User.Identity.Name == this.Application.RequesterNameEN)
            {
                return true;
            }
            return false;
        }
        private void ShowUploads()
        {
            HideUploads();

            if ((this.Application != null) && IsApplicationOwner())
            {
                if (this.Application.ApplicationType == "CR")
                {
                    IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                    FlowInstance flowInstance = queryService.QueryFlowInstance(this.id);
                    if (flowInstance != null)
                    {
                        if (flowInstance.CurrentActiveStep.StepCode == BEGDC.CC.BL.Workflow.WorkTransition.End)
                        {
                            this.tbUpload.Visible = true;
                            this.trCVFeedback.Visible = true;
                            return;
                        }
                    }
                }
            }

            if ((this.Application != null) && IsApplicationOwner())
            {
                if (this.Application.ApplicationType == "EV")
                {
                    IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                    FlowInstance flowInstance = queryService.QueryFlowInstance(this.id);
                    if (flowInstance != null)
                    {
                        if (flowInstance.CurrentActiveStep.StepCode == BEGDC.CC.BL.Workflow.WorkTransition.EV_MeetingMinutes)
                        {
                            this.tbUpload.Visible = true;
                            this.trEvMeetingMinutes.Visible = true;
                            return;
                        }
                    }
                }
            }

            if (this.readOnly)
            {
                //if readonly hide upload button
                this.tableAttachmentTitle.Visible = false;
                this.tr_Attach.Visible = false;
                return;
            }

            if (this.uploadType == UploadType.TEMPLATE)
            {
                //				this.btnAttach.Visible=true;
                this.dgAttachment.Visible = false;
                this.dgTemplate.Visible = true;
                this.lblListName.Text = "Templates List (模板类型)";
                this.lblUpload.Text = "Upload Template(Only txt,ppt,doc,xls,pdf,rar,zip files are allowed):<br>可上传的文件格式为txt,ppt,doc,xls,rar,zip。";
            }
            else
            {
                //				this.btnAttach.Visible=false;
                this.dgAttachment.Visible = true;
                this.dgTemplate.Visible = false;
                this.lblListName.Text = "Attachment List (附件列表)";
                this.lblUpload.Text = "Upload Attachment(Only txt,ppt,doc,xls,pdf,rar,zip files are allowed):<br>可上传的文件格式为txt,ppt,doc,xls,rar,zip。";
            }

            this.tbUpload.Visible = true;
            IList list = null;
            switch (this.uploadType)
            {
                case UploadType.APPLICATION:
                    list = AttachmentService.GetAttachmentToBeUpload(this.id);
                    if (list == null || list.Count == 0)
                    {
                        this.tr_Attach.Visible = false;
                        return;
                    }
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i].ToString() == AttachmentType.SUMMARY.ToString())
                        {
                            this.trSummary.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.AGENDA.ToString())
                        {
                            this.trAgenda.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.BUDGET.ToString())
                        {
                            this.trBudget.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.VISA.ToString())
                        {
                            this.trVisa.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.GIFT.ToString())
                        {
                            this.trGift.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.CONTRACT.ToString())
                        {
                            this.trContract.Visible = true;
                        }
                        //<--Joan 2007/8/2
                        else if (list[i].ToString() == AttachmentType.HOTEL.ToString())
                        {
                            this.trHotel.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.VEHICLE.ToString())
                        {
                            this.trVehicle.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.DEMOCENTER.ToString())
                        {
                            this.trDemo.Visible = true;
                        }
                        else if (list[i].ToString() == AttachmentType.ASBVISIT.ToString())
                        {
                            this.trASBVisit.Visible = true;
                        }
                        //-->end
                        else
                        {
                            this.trOthers.Visible = true;
                            //this.trOthers.Cells[0].InnerText="Other Documents:";
                        }
                    }
                    break;
                case UploadType.ACTIONPOINT:
                    this.tbUpload.Visible = true;
                    this.trOthers.Visible = true;
                    this.trOthers.Cells[0].InnerText = "Action Point Attachment:";
                    break;
                case UploadType.TEMPLATE:
                    this.tbUpload.Visible = true;
                    this.trTemplate.Visible = true;
                    //this.trSummary.Visible=true;
                    //this.trAgenda.Visible=true;
                    //this.trBudget.Visible=true;
                    //this.trVisa.Visible=true;
                    //this.trGift.Visible=true;
                    //this.trContract.Visible=true;

                    break;
                default:
                    break;
            }
        }

        private void HideUploads()
        {
            //hide upload form first
            this.tbUpload.Visible = false;
            //hide upload file controls
            this.trSummary.Visible = false;
            this.trAgenda.Visible = false;
            this.trBudget.Visible = false;
            this.trVisa.Visible = false;
            this.trGift.Visible = false;
            this.trContract.Visible = false;
            this.trOthers.Visible = false;
            this.trTemplate.Visible = false;
            //<--Joan 2007/8/2
            this.trHotel.Visible = false;
            this.trVehicle.Visible = false;
            this.trDemo.Visible = false;
            this.trASBVisit.Visible = false;
            this.trCVFeedback.Visible = false;
            this.trEvMeetingMinutes.Visible = false;
            //-->end

        }


        #endregion

        #region Web Form Designer generated code
        private void InitializeComponent()
        {
            this.btnAttach.Click += new EventHandler(btnAttach_Click);
            this.dgAttachment.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgAttachment_ItemCommand);
            this.dgAttachment.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgAttachment_ItemDataBound);
            this.dgTemplate.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgTemplate_ItemCommand);
            this.dgTemplate.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dgTemplate_SortCommand);
            this.dgTemplate.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgTemplate_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }

        void btnAttach_Click(object sender, EventArgs e)
        {
            this.SaveAttachment();
        }

        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        #endregion

        private void BindAttachment()
        {
            DataTable table = null;
            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            if (this.uploadType == UploadType.TEMPLATE)
            {
                table = query.GetTemplates();
                if (table != null)
                {
                    if (this._Sorting != string.Empty)
                    {
                        table.DefaultView.Sort = this._Sorting;
                    }

                    if (!(((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.BusinessAdmin) && ((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.OCOBusinessAdmin)))
                    {

                        if (((BEGDC.CC.BL.Workflow.CCPrincipal)Page.User).IsInRole(BL.Common.CODOrOCO.BusinessAdmin))
                        {
                            //table.DefaultView.RowFilter = "TemplateForApp NOT IN ('OCR-A','OCR-B','OCV','EBD-A','EBD-B','ESC-A','ESC-B','EBDCV','ESCCV')";
                            table.DefaultView.RowFilter = "TemplateForApp NOT IN ('IBGCR','IBGCV')";
                        }
                        else
                        {
                            table.DefaultView.RowFilter = "TemplateForApp IN ('IBGCR','IBGCV')";
                        }
                    }

                    this.dgTemplate.DataSource = table.DefaultView;
                    this.dgTemplate.DataBind();
                    if (this.readOnly)
                        this.dgTemplate.Columns[9].Visible = false;

                    //add to cache
                    AddTemplateCache(table);
                }

            }
            else
            {
                if (this.uploadType == UploadType.ACTIONPOINT && this.id > 0)
                    table = query.GetAttachmentByApId(id);
                else
                {
                    if (this.uploadType == UploadType.APPLICATION && this.id > 0)
                        table = query.GetAttachmentByAppId(id);
                }
                if (table != null)
                {
                    this.dgAttachment.DataSource = table;
                    this.dgAttachment.DataBind();
                    if (this.readOnly)
                        this.dgAttachment.Columns[7].Visible = false;
                }
            }
        }



        private void dgAttachment_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton btnDel = (ImageButton)e.Item.Cells[5].FindControl("btnDelAttach");
                string ItemId = e.Item.Cells[0].Text.ToString();
                if (btnDel != null)
                {
                    btnDel.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
                }
                //e.Item.Cells[1].Text="<a href='" +  e.Item.Cells[6].Text +"'>" + e.Item.Cells[5].Text + "</a>";

            }
        }

        private void dgTemplate_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton btnDel = (ImageButton)e.Item.Cells[7].FindControl("btnDelTemplate");
                string ItemId = e.Item.Cells[0].Text.ToString();
                if (btnDel != null)
                {
                    btnDel.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
                }
                //e.Item.Cells[1].Text="<a href='" +  e.Item.Cells[6].Text +"'>" + e.Item.Cells[5].Text + "</a>";
            }
        }

        public void SaveAttachment()
        {

            string fullPath;
            Attachment attach = null;
            Template template = null;
            IList listAttachs = new System.Collections.ArrayList();
            bool success = true;
            string errMsg = "";
            string errMsg1 = "";
            string notAllowed = "";

            try
            {
                AttachmentType attType = AttachmentType.AGENDA;
                if (this.uploadType == UploadType.TEMPLATE)
                {
                    #region get uploaded template

                    switch (this.drTemplateType.SelectedValue)
                    {
                        case "AGENDA":
                            attType = AttachmentType.AGENDA;
                            break;
                        case "BUDGET":
                            attType = AttachmentType.BUDGET;
                            break;
                        case "GIFT":
                            attType = AttachmentType.GIFT;
                            break;
                        case "VISA":
                            attType = AttachmentType.VISA;
                            break;
                        case "CONTRACT":
                            attType = AttachmentType.CONTRACT;
                            break;
                        case "HOTEL":
                            attType = AttachmentType.HOTEL;
                            break;
                        case "VEHICLE":
                            attType = AttachmentType.VEHICLE;
                            break;
                        case "DEMOCENTER":
                            attType = AttachmentType.DEMOCENTER;
                            break;
                        case "ASBVISIT":
                            attType = AttachmentType.ASBVISIT;
                            break;
                        case "ExecutiveSummary":
                            attType = AttachmentType.ExecutiveSummary;
                            break;
                        case "CRFeedback":
                            attType = AttachmentType.CRFeedback;
                            break;
                        case "EvMeetingMinutes":
                            attType = AttachmentType.EvMeetingMinutes;
                            break;
                        default:
                            break;

                    }

                    template = (Template)BuildAttachmentObj(this.fileTemplate, attType, this.uploadType, this.id, out notAllowed);
                    if (template != null)
                        listAttachs.Add(template);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    #region obsolete
                    /*
					template = (Template)BuildAttachmentObj(this.fileAgenda,AttachmentType.AGENDA,this.uploadType,this.id,out notAllowed);
					if (template != null)
						listAttachs.Add(template);
					else if (notAllowed!="" && notAllowed!=string.Empty)
					{
						errMsg += notAllowed + "format is not correct. \\n";
					}
					
					
					template = (Template)BuildAttachmentObj(this.fileBudget,AttachmentType.BUDGET,this.uploadType,this.id,out notAllowed);
					if (template != null)
						listAttachs.Add(template);
					else if (notAllowed!="" && notAllowed!=string.Empty)
					{
						errMsg += notAllowed + "format is not correct. \\n";
					}

					template = (Template)BuildAttachmentObj(this.fileGift,AttachmentType.GIFT,this.uploadType,this.id,out notAllowed);
					if (template != null)
						listAttachs.Add(template);
					else if (notAllowed!="" && notAllowed!=string.Empty)
					{
						errMsg += notAllowed + "format is not correct. \\n";
					}

					template = (Template)BuildAttachmentObj(this.fileVisa,AttachmentType.VISA,this.uploadType,this.id,out notAllowed);
					if (template != null)
						listAttachs.Add(template);
					else if (notAllowed!="" && notAllowed!=string.Empty)
					{
						errMsg += notAllowed + "format is not correct. \\n";
					}

					template = (Template)BuildAttachmentObj(this.fileContract,AttachmentType.CONTRACT,this.uploadType,this.id,out notAllowed);
					if (template != null)
						listAttachs.Add(template);
					else if (notAllowed!="" && notAllowed!=string.Empty)
					{
						errMsg += notAllowed + "format is not correct. \\n";
					}
					*/
                    #endregion
                    //Save template
                    if (listAttachs.Count > 0)
                        success = AttachmentService.SaveTemplates(listAttachs, out errMsg1);
                    errMsg += errMsg1;

                    #endregion
                }
                else
                {
                    #region Get Uploaded attachments
                    attach = (Attachment)BuildAttachmentObj(this.fileSummary, AttachmentType.SUMMARY, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileAgenda, AttachmentType.AGENDA, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileBudget, AttachmentType.BUDGET, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileVisa, AttachmentType.VISA, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileGift, AttachmentType.GIFT, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileContract, AttachmentType.CONTRACT, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    #region //<--Joan 2007/8/2, special attachment for OCO
                    //Hotel Booking Form
                    attach = (Attachment)BuildAttachmentObj(this.fileHotel, AttachmentType.HOTEL, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }
                    //Vehicle Booking Form
                    attach = (Attachment)BuildAttachmentObj(this.fileVehicle, AttachmentType.VEHICLE, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }
                    //Demo Center application
                    attach = (Attachment)BuildAttachmentObj(this.fileDemo, AttachmentType.DEMOCENTER, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }
                    //ASB Visit Arrangement
                    attach = (Attachment)BuildAttachmentObj(this.fileASBVisit, AttachmentType.ASBVISIT, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }
                    #endregion//-->end

                    attach = (Attachment)BuildAttachmentObj(this.fileCVFeedback, AttachmentType.CRFeedback, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }

                    attach = (Attachment)BuildAttachmentObj(this.fileEvMeetingMinutes, AttachmentType.EvMeetingMinutes, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }


                    attach = (Attachment)BuildAttachmentObj(this.fileOthers, AttachmentType.OTHERS, this.uploadType, this.id, out notAllowed);
                    if (attach != null)
                        listAttachs.Add(attach);
                    else if (notAllowed != "" && notAllowed != string.Empty)
                    {
                        errMsg += notAllowed + "format is not correct. \\n";
                    }
                    //Save attachments
                    if (listAttachs.Count > 0)
                        success = AttachmentService.SaveAttachments(listAttachs, out errMsg1);
                    errMsg += errMsg1;

                }

                    #endregion
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('Unknown error occured, please contact system admin.');</script>");
            }

            BindAttachment();
            if (this.uploadType != UploadType.TEMPLATE)
            {
                // message popup 
                if (success && (errMsg == "" || errMsg == string.Empty))
                {
                    string url = Request.Form["tbURL"];
                    string script = "<script>";
                    if (url == string.Empty)
                    {
                        if (listAttachs.Count > 0)
                            script += "alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                    }
                    if (url != string.Empty && url != null && url != "")
                        script += "window.location.href='" + url + "'";
                    script += "</script>";

                    Page.RegisterClientScriptBlock("", script);
                }
                else
                    Page.RegisterClientScriptBlock("", "<script>alert('" + errMsg + "');</script>");
            }
            else
            {
                if (success && (errMsg == "" || errMsg == string.Empty) && listAttachs.Count > 0)
                {
                    //Edited by John
                    Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");
                }
                else
                    Page.RegisterClientScriptBlock("", "<script>alert('" + errMsg + "');</script>");
            }
        }

        private object BuildAttachmentObj(HtmlInputFile file, AttachmentType fileType, UploadType upldType, int id, out string notAllowed)
        {
            BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
            DataTable dt = queryService.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ATTACHMENTTYPE);
            string appDocRoot = BEGDC.CC.BL.Workflow.Configuration.AttachmentPath;

            Attachment attach = null;
            Template temp = null;
            string fullPath;
            string relativePath;
            string fileName;
            string fileExt = "txt,ppt,doc,xls,pdf,rar,zip";
            string strExt;
            notAllowed = string.Empty;
            fileExt = fileExt.ToUpper();

            if (!(file.PostedFile == null || file.PostedFile.FileName + "" == ""))
            {
                if (upldType == UploadType.ACTIONPOINT || upldType == UploadType.APPLICATION)
                {
                    #region Appliction or AcctionPoint
                    relativePath = WebUtility.GetDocumentStoredPath(appDocRoot, file.PostedFile.FileName, out fullPath);
                    fileName = System.IO.Path.GetFileName(fullPath).Substring(5);

                    //check if the file is allowed to be uploaded
                    strExt = fileName.Substring(fileName.Length - 3).ToUpper();
                    if (fileExt.IndexOf(strExt) < 0)
                    {
                        notAllowed = GenerateNotAllowedMessage(fileType);
                        return null;
                    }

                    file.PostedFile.SaveAs(fullPath);
                    attach = new Attachment();
                    attach.FileName = fileName;

                    attach.FilePath = fullPath;
                    if (upldType == UploadType.APPLICATION)
                    {
                        attach.Application = new Application();
                        attach.Application.Id = id;
                    }
                    else
                    {
                        attach.ActionPoint = new ActionPoint();
                        attach.ActionPoint.Id = id;
                    }
                    attach.Owner = HttpContext.Current.User.Identity.Name;
                    attach.Date = System.DateTime.Now;

                    attach.AttachmentType = new DicItem();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["DicItemKey"].ToString() == fileType.ToString())
                        {
                            attach.AttachmentType.Id = Convert.ToInt32(dt.Rows[i]["DicItemID"]);
                            attach.AttachmentType.DicItemKey = dt.Rows[i]["DicItemKey"].ToString();
                            break;
                        }
                    }
                    return attach;
                    #endregion
                }

                else
                {
                    #region Template
                    relativePath = WebUtility.GetDocumentStoredPath(appDocRoot, file.PostedFile.FileName, out fullPath);
                    fileName = System.IO.Path.GetFileName(fullPath).Substring(5);


                    //check if the file is allowed to be uploaded
                    strExt = fileName.Substring(fileName.Length - 3).ToUpper();
                    if (fileExt.IndexOf(strExt) < 0)
                    {
                        notAllowed = GenerateNotAllowedMessage(fileType);
                        return null;
                    }

                    file.PostedFile.SaveAs(fullPath);
                    temp = new Template();
                    temp.FileName = fileName;
                    temp.FilePath = fullPath;
                    temp.Owner = HttpContext.Current.User.Identity.Name;
                    temp.LastUpdate = System.DateTime.Now;
                    temp.TemplateType = new DicItem();
                    temp.TemplateForApp = this.drFlowType.SelectedValue;
                    temp.TemplateOrSample = this.drSample.SelectedValue;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["DicItemKey"].ToString() == fileType.ToString())
                        {
                            temp.TemplateType.Id = Convert.ToInt32(dt.Rows[i]["DicItemID"]);
                            temp.TemplateType.DicItemKey = dt.Rows[i]["DicItemKey"].ToString();
                            break;
                        }
                    }
                    return temp;
                    #endregion
                }

            }
            return null;

        }


        private string GenerateNotAllowedMessage(AttachmentType fileType)
        {
            switch (fileType)
            {
                case AttachmentType.SUMMARY:
                    return "Excutive Summary ";
                    break;
                case AttachmentType.AGENDA:
                    return "Agenda ";
                    break;
                case AttachmentType.BUDGET:
                    return "Budget Breakdown ";
                    break;
                case AttachmentType.GIFT:
                    return "Gift Request Form ";
                    break;
                case AttachmentType.VISA:
                    return "Vise Request Form ";
                    break;
                case AttachmentType.CONTRACT:
                    return "Contract Memo Or Agreement ";
                    break;
                //<--Joan 2008/8/2
                case AttachmentType.HOTEL:
                    return "Hotel Booking Form ";
                    break;
                case AttachmentType.VEHICLE:
                    return "Vehicle Booking Form ";
                    break;
                case AttachmentType.DEMOCENTER:
                    return "Demo Center Visit Application ";
                    break;
                case AttachmentType.ASBVISIT:
                    return "ASB Visit Arrangement Form ";
                    break;

                //-->
                case AttachmentType.OTHERS:
                    return "Other Documents ";
                    break;

                default:
                    break;
            }
            return "";
        }

        private void dgTemplate_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            bool success = true;
            string errMsg = "";

            if (e.CommandName == "Delete")
            {
                string templateID = e.Item.Cells[0].Text;
                success = AttachmentService.DeleteFileByID(this.uploadType, Convert.ToInt32(templateID), errMsg);
            }
            //			else if( e.CommandName == "Download" )
            //			{
            //				OutPutFile(e.Item.Cells[6].Text,e.Item.Cells[5].Text, out errMsg);
            //			}

            // message popup
            if (errMsg != "")
                Page.RegisterClientScriptBlock("", "<script>alert('" + errMsg + "');</script>");

            BindAttachment();

        }
        private void dgAttachment_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            bool success = true;
            string errMsg = "";

            if (e.CommandName == "Delete")
            {
                string fileId = e.Item.Cells[0].Text;
                success = AttachmentService.DeleteFileByID(this.uploadType, Convert.ToInt32(fileId), errMsg);
            }
            //			else if( e.CommandName == "Download" )
            //			{
            //				OutPutFile(e.Item.Cells[6].Text,e.Item.Cells[5].Text,out errMsg);
            //			}

            // message popup
            if (errMsg != "")
                Page.RegisterClientScriptBlock("", "<script>alert('" + errMsg + "');</script>");

            //				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");
            //			else

            BindAttachment();

        }
        private void OutPutFile(string sourceFile, string fileName, out string errMsg)
        {
            System.IO.FileStream fileStream = new System.IO.FileStream(sourceFile, System.IO.FileMode.Open);
            errMsg = "";
            try
            {
                long fileSize = fileStream.Length;
                Response.Buffer = true;

                Response.ContentType = "application/octet-stream";
                //中文文件名需要UTF8编码
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
                Response.AddHeader("Content-Length", fileSize.ToString());
                byte[] fileBuffer = new byte[fileSize];
                fileStream.Read(fileBuffer, 0, (int)fileSize);

                Response.BinaryWrite(fileBuffer);
                Response.Flush();
                Response.End();
            }
            catch (Exception exp)
            {
                errMsg = exp.Message;
            }

            finally
            {
                fileStream.Close();
            }
        }

        private void AddTemplateCache(DataTable table)
        {
            DataTable tempTable;
            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            if (table == null)
                tempTable = query.GetTemplates();
            else
                tempTable = table;

            //add to cache
            if (tempTable != null)
            {
                if (HttpContext.Current.Cache["Template"] == null)
                    HttpContext.Current.Cache.Add("Template", tempTable, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                        CacheItemPriority.Default, null);
                else
                {
                    HttpContext.Current.Cache.Remove("Template");
                    HttpContext.Current.Cache.Add("Template", tempTable, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                        CacheItemPriority.Default, null);
                }
            }
        }


        #region Add by Alan 2007/7/25
        public void dgTemplate_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            if (this._Sorting.IndexOf(e.SortExpression) > -1 && this._Sorting == e.SortExpression)
                this._Sorting = e.SortExpression + " desc";
            else
                this._Sorting = e.SortExpression;
            this.BindAttachment();

        }
        #endregion
    }
}
